import config from '@/config/index'
import { router } from '@/router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

/**
封装的fetch请求函数
 */
export default async function request<T = any>({
  url,
  method,
  header,
  data
}: any): Promise<T | string | Blob> {
  const options: any = {
    method: method.toUpperCase() ?? 'GET',
    headers: {},
    mode: 'cors',
    credentials: 'same-origin'
  }
  const re = /^http/

  // 判断header
  if (header) {
    options.headers = header
  } else {
    if (data instanceof FormData) {
      // 传FormData对象不能设Content-Type
      options.body = data
    } else {
      // 传JSON字符串
      options.headers = {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      }
      options.body = JSON.stringify(data)
    }
  }

  //添加jwt token
  options.headers['Authorization'] = `Bearer ${useUserStore().token}`

  function checkError(code, message?) {
    switch (code) {
      case 500: {
        ElMessage({
          type: 'error',
          message: message ?? '服务器系统内部错误'
        })
        break
      }

      case 204: {
        ElMessage({
          type: 'error',
          message: message ?? '无内容'
        })
        break
      }

      case 400: {
        ElMessage({
          type: 'error',
          message: message ?? '请求错误'
        })
        break
      }

      case 401: {
        ElMessage({
          type: 'error',
          message: message ?? '请登录'
        })

        router.push('/login')
        break
      }

      case 403: {
        ElMessage({
          type: 'error',
          message: message ?? '无权限执行此操作'
        })
        break
      }

      case 404: {
        ElMessage({
          type: 'error',
          message: message ?? '地址错误'
        })
        break
      }

      default: {
        ElMessage({
          type: 'error',
          message: message ?? '请求失败'
        })
        break
      }
    }
  }
  //开始请求
  let response
  try {
    response = await fetch(re.test(url) ? url : config.baseUrl + url, options)
  } catch (error) {
    checkError(0, error.message)

    return error
  }

  const contentType = response.headers.get('Content-Type')

  //判断请求是否成功
  if (response.ok) {
    if (contentType?.includes('application/json')) {
      const res = await response.json()
      if (res.code != 200) checkError(res.code, res.message)
      return res
    } else if (contentType?.includes('text/html')) return response.text()
    else return response.blob()
  } else {
    if (contentType?.includes('application/json')) {
      const res = await response.json()
      checkError(res.code, res.message)
      return res
    }

    checkError(response.status, response.statusText)
    return response
  }
}
